package com.zdkj.subway.stm.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.dto.out.SwParamStation;
import com.zdkj.subway.stm.dto.out.SwPmTicketCardTypeDto;
import com.zdkj.subway.stm.dto.out.SwPmTicketCardTypeParamDto;
import com.zdkj.subway.stm.entity.SwStConductorSellDetail;
import com.zdkj.subway.stm.entity.SwStConductorSettle;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.mapper.SwStConductorSellDetailMapper;
import com.zdkj.subway.stm.service.SwStConductorSellDetailService;
import com.zdkj.subway.stm.util.DateUtilStm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 车站车票售卖详细信息
 *
 * @author songtuo
 * @date 2020-07-14 11:52:25
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstconductorselldetail")
@Api(value = "swstconductorselldetail", tags = "车站车票售卖详细信息管理")
@Slf4j
public class SwStConductorSellDetailController {

    private final SwStConductorSellDetailService swStConductorSellDetailService;
    private final SupportService supportService;
    @Resource
    SwStConductorSellDetailMapper swStConductorSellDetailMapper;

    /**
     * 分页查询
     *
     * @param page                    分页对象
     * @param swStConductorSellDetail 车站车票售卖详细信息
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStConductorSellDetailPage(Page page, SwStConductorSellDetail swStConductorSellDetail) {
        SwStConductorSellDetail swStConductorSellDetailObj = ObjectUtils.getDefaultObj(SwStConductorSellDetail.class);
        swStConductorSellDetail.setLineCode(swStConductorSellDetailObj.getLineCode());
        swStConductorSellDetail.setStationCode(swStConductorSellDetailObj.getStationCode());
        QueryWrapper<SwStConductorSellDetail> lambdaQueryWrapper = Wrappers.query(swStConductorSellDetail).orderByDesc("ISSUE_TIME");
        //售卖时间
        List<String> dateCondition = swStConductorSellDetail.getDates1();
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            lambdaQueryWrapper.lambda().between(SwStConductorSellDetail::getIssueTime, dateCondition.get(0), dateCondition.get(1));
        }
        return R.ok(swStConductorSellDetailService.page(page, lambdaQueryWrapper));
        //return R.ok(swStConductorSellDetailService.page(page, Wrappers.query(swStConductorSellDetail).orderByDesc("ISSUE_TIME")));
    }


    /**
     * 通过id查询车站车票售卖详细信息
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStConductorSellDetailService.getById(id));
    }

    /**
     * 新增车站车票售卖详细信息
     *
     * @param swStConductorSellDetail 车站车票售卖详细信息
     * @return R
     */
    @ApiOperation(value = "新增车站车票售卖详细信息", notes = "新增车站车票售卖详细信息")
    @SysLog("新增车站车票售卖详细信息")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swstconductorselldetail_add')")
    public R save(@RequestBody SwStConductorSellDetail swStConductorSellDetail) {
        return R.ok(swStConductorSellDetailService.save(swStConductorSellDetail));
    }

    /**
     * 修改车站车票售卖详细信息
     *
     * @param swStConductorSellDetail 车站车票售卖详细信息
     * @return R
     */
    @ApiOperation(value = "修改车站车票售卖详细信息", notes = "修改车站车票售卖详细信息")
    @SysLog("修改车站车票售卖详细信息")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swstconductorselldetail_edit')")
    public R updateById(@RequestBody SwStConductorSellDetail swStConductorSellDetail) {
        return R.ok(swStConductorSellDetailService.updateById(swStConductorSellDetail));
    }

    /**
     * 通过id删除车站车票售卖详细信息
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除车站车票售卖详细信息", notes = "通过id删除车站车票售卖详细信息")
    @SysLog("通过id删除车站车票售卖详细信息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('swstconductorselldetail_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStConductorSellDetailService.removeById(id));
    }


    @ApiOperation(value = "导出车站车票售卖详情数据", notes = "导出车票售卖详情数据")
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('swstconductorselldetail_export')")
    public void export(@RequestParam(value = "ids") List<Integer> ids, HttpServletResponse response) {
        List<SwStConductorSellDetail> records;
        PigxUser user = SecurityUtils.getUser();
        Map<String,String> params = new HashMap<>();
        params.put("lineCode",user.getLineCode());
        params.put("stationCode",user.getStationCode());
        records = swStConductorSellDetailMapper.queryExport(ids,params);
        //List<SwStConductorSellDetail> records = swStConductorSellDetailService.page(page, Wrappers.query(stConductorSellDetail)).getRecords();

        /*List<SwStConductorSellDetail> newSellDetailList=new ArrayList<>();
        R<List<SwPmTicketCardTypeDto>> cardTypeDict= supportService.getCardTypeDict(SecurityConstants.FROM_IN);
        List<SwPmTicketCardTypeDto> cardTypeDictList=cardTypeDict.getData();
        for (SwStConductorSellDetail record : records) {
            for (SwPmTicketCardTypeDto swPmTicketCardTypeDto : cardTypeDictList) {
                if(record.getCardType().equals(swPmTicketCardTypeDto.getMainEnName())){
                    record.setCardType(swPmTicketCardTypeDto.getMainName());
                    R<List<SwPmTicketCardTypeParamDto>> cardTypeParamDict= supportService.getCardTypeParamDict(swPmTicketCardTypeDto.getMainEnName(),SecurityConstants.FROM_IN);
                    for (SwPmTicketCardTypeParamDto swPmTicketCardTypeParamDto : cardTypeParamDict.getData()) {
                        if(record.getTicketName().equals(swPmTicketCardTypeParamDto.getSubEnName())){
                            record.setTicketName(swPmTicketCardTypeParamDto.getSubName());
                        }
                    }
                    newSellDetailList.add(record);

                }
            }
        }*/
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("车站车票售卖信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStConductorSellDetail.class).
                    sheet("导出车站车票售卖信息数据失败").doWrite(records);
        } catch (IOException e) {
            log.error("导出车站车票售卖信息数据失败");
        }
    }

    /**
     * 定时任务调用，定时计算前一天的数据
     *
     * @return
     */
    @ApiOperation(value = "统计前一天的车票售卖详情数据", notes = "统计前一天的车票售卖详情数据")
    @Inner
    @PostMapping("/calc")
    public R calcByDaily() {
        String date = DateUtilStm.asPreDateString(LocalDateTime.now());
        List<SwStConductorSellDetail> listSell = swStConductorSellDetailService.querySell(date);
        //配备用金归还时的废票
        List<SwStConductorSellDetail> listInvalid = swStConductorSellDetailService.queryInvalid(date);
        //乘客事务退换票
        List<SwStConductorSellDetail> listPassenger = swStConductorSellDetailService.queryPassenger(date);
        listSell.addAll(listInvalid);
        listSell.addAll(listPassenger);
        listSell.forEach(detail -> {
            SwStConductorSellDetail detailDB = swStConductorSellDetailService.getOne(Wrappers.
                    <SwStConductorSellDetail>query().lambda()
                    .eq(SwStConductorSellDetail::getCardType, detail.getCardType())
                    .eq(SwStConductorSellDetail::getLineCode, detail.getLineCode())
                    .eq(SwStConductorSellDetail::getStationCode, detail.getStationCode())
                    .eq(SwStConductorSellDetail::getConductorJobNo, detail.getConductorJobNo())
                    .eq(SwStConductorSellDetail::getTicketName, detail.getTicketName())
                    .eq(SwStConductorSellDetail::getIssueType, detail.getIssueType())
                    .eq(SwStConductorSellDetail::getIssueTime, detail.getIssueTime()));
            if (null != detailDB) {
                //找到就更新
                detail.setId(detailDB.getId());
            }
        });
        return R.ok(swStConductorSellDetailService.saveOrUpdateBatch(listSell));
    }
}
